"""
打包日志+报告，同时发企业微信+钉钉
"""
import logging
import os
import requests


logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")



# ========== 企业微信：==========
WX_UPLOAD_URL = "https://qyapi.weixin.qq.com/cgi-bin/media/upload"
WX_SEND_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send"


def wx_get_token(corpid, secret):
    url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}"
    response = requests.get(url)
    result = response.json()
    if result.get("errcode") == 0:
        return result["access_token"]
    else:
        logging.error(f"获取token失败: {result}")
        return None


def wx_send_file(token, agent_id, zip_path):
    try:
        # 1. 上传文件
        with open(zip_path, "rb") as file:
            files = {"media": (os.path.basename(zip_path), file, "application/zip")}
            data = {"type": "file"}



            up_resp = requests.post(
                WX_UPLOAD_URL,
                params={"access_token": token},
                files=files,
                data=data,
            )
            up_result = up_resp.json()

            # 检查上传是否成功
            if up_result.get("errcode") !=0:
                logging.error(f"文件上传失败: {up_result}")
                return up_result

            media_id = up_result["media_id"]
            logging.info(f"文件上传成功，media_id: {media_id}")

        # 2. 发消息
        payload = {
            "touser": "@all",
            "msgtype": "file",
            "agentid": agent_id,
            "file": {"media_id": media_id},
            "safe": 0
        }

        resp = requests.post(
            WX_SEND_URL,
            params={"access_token": token},
            json=payload
        ).json()

        logging.info("企业微信发送结果：%s", resp)
        return resp

    except Exception as e:
        logging.error(f"企业微信发送文件异常: {e}")
        return {"errcode": -1, "errmsg": str(e)}



# ========== 钉钉：机器人发文件 ==========
DING_FILE_URL = "https://oapi.dingtalk.com/robot/send"
def inner_upload_file(app_key, app_secret, chat_id, zip_path):
    # 1. 获取 token
    token_url = f"https://oapi.dingtalk.com/gettoken?appkey={app_key}&appsecret={app_secret}"
    r1 = requests.get(token_url)
    print('[token] status:', r1.status_code, 'text:', repr(r1.text))
    token = r1.json()['access_token']

    # 2. 上传文件
    upload_url = "https://oapi.dingtalk.com/media/upload"
    params = {"access_token": token, "type": "file"}

    with open(zip_path, "rb") as f:
        files = {"media": (os.path.basename(zip_path), f, "application/zip")}
        response = requests.post(upload_url, params=params, files=files)

    logging.info(f"上传响应: {response.text}")
    result = response.json()
    if result.get("errcode") != 0:
        logging.error(f"上传失败: {result}")
        return
    media_id = result["media_id"]
    print("上传成功 media_id:", media_id)

    # 3. 发群文件
    send_url = "https://oapi.dingtalk.com/chat/send"
    msg = {
        "chatid": chat_id,
        "msg": {
            "msgtype": "file",
            "file": {"media_id": media_id}
        }
    }
    r3 = requests.post(send_url, params={"access_token": token}, json=msg)
    print('[send] status:', r3.status_code, 'text:', repr(r3.text))

